import Cookies from 'js-cookie'

const TokenKey = 'juejin-vue-m_token'

const timeKey = 'juejin-vue-m_token-time' // 用来作为时间戳存储的key
// const keywords = 'web_keywords'
const userInfo = 'userInfo'
export function getToken () {
  return Cookies.get(TokenKey)
}

export function setToken (token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken () {
  return Cookies.remove(TokenKey)
}

export function setTimeStamp () {
  // Date.now()  new Date.getTime()
  Cookies.set(timeKey, Date.now())
}

export function getTimeStamp () {
  return Cookies.get(timeKey)
}

export function removeTimeStamp () {
  return Cookies.remove(timeKey)
}

export function getUserInfo () {
  return JSON.parse(localStorage.getItem('userInfo'))
}
export function setUserInfo (info) {
  return localStorage.setItem(userInfo, JSON.stringify(info))
}
export function removeUserInfo () {
  return localStorage.clear(userInfo)
}

// export function getKeywords () {
//   return JSON.parse(localStorage.getItem(keywords))
// }
// export function setKeywords (i) {
//   return localStorage.setItem(keywords, JSON.stringify(i))
// }
// export function removeKeywords () {
//   return localStorage.clear(keywords)
// }

// 封装
export const getItem = name => {
  const data = window.localStorage.getItem(name)
  // 为什么把JSON.parse 放到 try-catch 中？
  // 因为 data 可能不是 JSON 格式的字符串
  try {
    return JSON.parse(data)
  } catch (error) {
    return data
  }
}

export const setItem = (name, value) => {
  // 如果 value 是对象，就把 value 转为 JSON 格式的字符串再存储
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  window.localStorage.setItem(name, value)
}

export const removeItem = name => {
  window.localStorage.removeItem(name)
}
